var app = angular.module('users', ['ngGrid', 'ui.bootstrap']);

// Create a controller with name "usersList" to bind to the HTML page.
app.controller('usersList', function($scope, userRestWs) {
    // Refresh the grid, calling the appropriate service method.
    $scope.refreshGrid = function(page) {
        userRestWs.listUsers(page, $scope.sortInfo.fields[0], $scope.sortInfo.directions[0]).success(function(data) {
            $scope.users = data;
        });
    };

    // Do something when the grid is sorted.
    // The grid throws the ngGridEventSorted that gets picked up here and assigns the sortInfo to the scope.
    // This will allow to watch the sortInfo in the scope for changed and refresh the grid.
    $scope.$on('ngGridEventSorted', function(event, sortInfo) {
        $scope.sortInfo = sortInfo;
    });

    // Watch the sortInfo variable. If changes are detected than we need to refresh the grid.
    // This also works for the first page access, since we assign the initial sorting in the initialize section.
    $scope.$watch('sortInfo.fields[0]', function() {
        $scope.refreshGrid($scope.users.currentPage);
    }, true);

    // Initialize required information: sorting, the first page to show and the grid options.
    $scope.sortInfo = {fields: ['id'], directions: ['asc']};
    $scope.users = {currentPage: 1};
    $scope.gridOptions = {
        data: 'users.list',
        useExternalSorting: true,
        sortInfo: $scope.sortInfo
    };
});

// REST Service that provides users operations
app.service('userRestWs', function($http) {
    // Makes the REST request to get the data to populate the grid.
    this.getAll = function(page, sortField, sortDirection) {
        return $http.get('resources/users/list', {
            params: {
                page: page,
                // FIXME adjust page size over here
                pageSize: 25,
                sortField: sortField,
                sortDirection: sortDirection
            }});
    };
});